import Vue from 'vue'
import Vuex from 'vuex'
import home from './modules/home'
import course from './modules/course'
import { fetchUser, validateUser } from '@/api/user.js'
// import VuexPersist from 'vuex-persist'


Vue.use(Vuex)




// const persist = new VuexPersist({
//   storage:window.localStorage,
// })
export default new Vuex.Store({
  // plugins:[persist.plugin],
  modules: {
    home,
    course
  },
  state: {
    user: {},
    hasPermission:false,
    menuPermission:false
  },
  mutations: {
    setLogin(state, payload) {
      state.user = payload
      state.hasPermission = true
    },
    validateUser(state, user) {
      state.user = user
      state.hasPermission = true
    },
    setMenuList(state,payload){
      state.menuPermission = true
    }
  },
  actions: {
    async setLogin({ commit }, user) {
      try{
        let result = await fetchUser(user);
        commit('setLogin', result);
        localStorage.setItem('token', result.token)
      }catch(e){
        return Promise.reject(e)
      }
    },
    async validateUser({ commit }) {
      try{
        let user = await validateUser()
        commit('validateUser', user)
      }catch(e){
        return new Promise.reject(e)
      }

    }
  },

})
